package com.stylefeng.guns.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.PfFileMapper;
import com.stylefeng.guns.common.persistence.dao.WzCouponMapper;
import com.stylefeng.guns.common.persistence.dao.WzPrizeMapper;
import com.stylefeng.guns.common.persistence.model.PfFile;
import com.stylefeng.guns.common.persistence.model.WzCoupon;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.wz.dao.WzPrizeDao;
import com.stylefeng.guns.modular.wz.warpper.PfFileWarpper;
import com.stylefeng.guns.modular.wz.warpper.WzCouponWarpper;
import com.stylefeng.guns.modular.wz.warpper.WzPrizeWarpper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.common.persistence.model.WzPrize;
import com.stylefeng.guns.modular.wz.service.IWzPrizeService;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 奖品控制器
 *
 * @author fengshuonan
 * @Date 2018-03-29 09:30:02
 */
@Controller
@RequestMapping("/wzPrize")
public class WzPrizeController extends BaseController {

    private String PREFIX = "/wz/wzPrize/";
    @Autowired
    private IWzPrizeService wzPrizeService;
    @Autowired
    private WzPrizeDao wzPrizeDao;
    @Autowired
    private PfFileMapper fileMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;

    /**
     * 跳转到奖品首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "wzPrize.html";
    }

    /**
     * 跳转到添加奖品
     */
    @RequestMapping("/wzPrize_add")
    public String wzPrizeAdd() {
        return PREFIX + "wzPrize_add.html";
    }

    /**
     * 跳转到修改奖品
     */
    @RequestMapping("/wzPrize_update/{wzPrizeId}")
    public String wzPrizeUpdate(@PathVariable Long wzPrizeId, Model model) {
        WzPrize wzPrize = wzPrizeService.selectById(wzPrizeId);
        model.addAttribute("item",wzPrize);
        model.addAttribute("type", ConstantFactory.me().getDictsByName("奖品类型", wzPrize.getType()));
        model.addAttribute("status", ConstantFactory.me().getDictsByName("奖品状态", wzPrize.getStatus()));
        model.addAttribute("subtype", ConstantFactory.me().getDictsByName("奖品子类型", wzPrize.getSubtype()));
        model.addAttribute("exchangeAmount", wzPrize.getExchangeAmount()/100);
        model.addAttribute("fileId", "");
        model.addAttribute("couponId", "");
        List<PfFile> files = fileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",wzPrize.getCoverUrl()));
        if(files.size() > 0){
            model.addAttribute("fileId", files.get(0).getFileId());
        }
        List<WzCoupon> coupons = couponMapper.selectList(new EntityWrapper<WzCoupon>().eq("prize_id",wzPrize.getPrizeId()));
        if(coupons.size() > 0){
            model.addAttribute("couponId", coupons.get(0).getCouponId());
        }
        LogObjectHolder.me().set(wzPrize);
//        String details=wzPrize.getDetails();
//        details=details.replaceAll("& lt;","<");
//        details=details.replaceAll("& gt;",">");
//        model.addAttribute("details",details);
        return PREFIX + "wzPrize_edit.html";
    }

    /**
     * 获取奖品列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        Page<WzPrize> page = new PageFactory<WzPrize>().defaultPage();
        List<Map<String, Object>> list = prizeMapper.selectMapsPage(page,new EntityWrapper<WzPrize>().orderBy("status",true).orderBy("create_time",false));
        page.setRecords((List<WzPrize>) new WzPrizeWarpper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 新增奖品
     */
    @Transactional
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(WzPrize wzPrize,String detail,String couponId,String fileId) {
        PfFile file = fileMapper.selectById(fileId);
        if(file != null){
            wzPrize.setCoverUrl(file.getFileUrl());
        }else{
            return super.SUCCESS_TIP.fail("封面图片不存在!");
        }
        WzCoupon coupon = couponMapper.selectById(couponId);
        if(coupon == null){
            return super.SUCCESS_TIP.fail("奖券不存在!");
        }else{
            if(coupon.getStatus() != 1){
                return super.SUCCESS_TIP.fail("奖券已被使用!");
            }
        }

        if(wzPrize.getContentType() == 2){//富文本
            if(!StringUtils.isNotBlank(wzPrize.getContent())){
                return super.SUCCESS_TIP.fail("富文本内容不能为空!");
            }
        }else if(wzPrize.getContentType() == 1){//自定义内容
            if(!StringUtils.isNotBlank(detail)){
                return super.SUCCESS_TIP.fail("自定义内容不能为空!");
            }
            detail = detail.trim().replace("style=\"width: ","");
            detail = detail.replace("px;\"","");
            detail = detail.replace("img","img style=\"height:auto; width:100%\"");
            wzPrize.setDetails(detail);
        }


        wzPrize.setCreateTime(new Date());
        wzPrize.setModifierId(ShiroKit.getUser().getId());
        wzPrize.setModifierName(ShiroKit.getUser().getName());
        wzPrize.setPayAmount(100);
        wzPrize.setStock(wzPrize.getQuantity());
        wzPrize.setStatus(1);
        wzPrize.setExchangeAmount(wzPrize.getExchangeAmount()*100);
        wzPrizeService.insert(wzPrize);

        coupon.setPrizeId(wzPrize.getPrizeId());
        coupon.setStatus(2);
        couponMapper.updateById(coupon);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除奖品
     */
    @Transactional
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long wzPrizeId) {
        WzPrize prize = wzPrizeService.selectById(wzPrizeId);
        if(prize.getStatus() == 1){
            wzPrizeService.deleteById(wzPrizeId);
            couponMapper.delete(new EntityWrapper<WzCoupon>().eq("prize_id",prize.getPrizeId()));
            return SUCCESS_TIP;
        }else{
            return SUCCESS_TIP.fail("只有待审核奖品才可删除!");
        }
    }

    /**
     * 发布奖品
     */
    @Transactional
    @RequestMapping(value = "/up")
    @ResponseBody
    public Object up(@RequestParam Long wzPrizeId) {
        WzPrize prize = wzPrizeService.selectById(wzPrizeId);
        if(prize.getStatus() == 1){
            prize.setStatus(2);
            wzPrizeService.updateById(prize);
            return SUCCESS_TIP;
        }else{
            return SUCCESS_TIP.fail("只有待审核奖品才可发布!");
        }
    }

    /**
     * 修改奖品
     */
    @Transactional
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(WzPrize wzPrize,String couponId,String fileId,String detail) {
        PfFile file = fileMapper.selectById(fileId);
        if(file != null){
            wzPrize.setCoverUrl(file.getFileUrl());
        }else{
            return super.SUCCESS_TIP.fail("封面图片不存在!");
        }
        //奖券

        List<WzCoupon> coupons = couponMapper.selectList(new EntityWrapper<WzCoupon>().eq("prize_id",wzPrize.getPrizeId()));
        WzCoupon coupon = couponMapper.selectById(couponId);
        if(coupon == null){
            return super.SUCCESS_TIP.fail("奖券不存在!");
        }else{
            if(coupon.getStatus() != 1 && coupon.getPrizeId() != coupons.get(0).getPrizeId()){
                return super.SUCCESS_TIP.fail("奖券已被使用!");
            }
        }
        if(coupon.getPrizeId() != coupons.get(0).getPrizeId()){
            coupon.setPrizeId(wzPrize.getPrizeId());
            coupon.setStatus(2);
            couponMapper.updateById(coupon);
            coupons.get(0).setStatus(1);
            coupons.get(0).setPrizeId(0L);
            couponMapper.updateById(coupons.get(0));
        }

        if(wzPrize.getContentType() == 2){//自定义
            if(!StringUtils.isNotBlank(wzPrize.getContent())){
                return super.SUCCESS_TIP.fail("自定义内容不能为空!");
            }
        }else if(wzPrize.getContentType() == 1){//富文本
            if(!StringUtils.isNotBlank(detail)){
                return super.SUCCESS_TIP.fail("富文本内容不能为空!");
            }
            detail = detail.trim().replace("style=\"width: ","");
            detail = detail.replace("px;\"","");
            detail = detail.replace("img","img style=\"height:auto; width:100%\"");
            wzPrize.setDetails(detail);
        }

        wzPrize.setExchangeAmount(wzPrize.getExchangeAmount()*100);
        wzPrize.setDetails(detail);
        wzPrize.setUpdateTime(new Date());
        wzPrizeService.updateById(wzPrize);
        return super.SUCCESS_TIP;
    }

    /**
     * 奖品详情
     */
    @RequestMapping(value = "/detail/{wzPrizeId}")
    @ResponseBody
    public Object detail(@PathVariable("wzPrizeId") Integer wzPrizeId) {
        return wzPrizeService.selectById(wzPrizeId);
    }
}
